#include "logwriter.h"

#include "core/coredefine.h"
#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QMutex>

//#define LOG_TO_FILE
#define LOG_TO_CONSOLE

static LogWriter* log_writer = nullptr;
LogWriter* LogWriter::getInstance()
{
    if (nullptr == log_writer)
    {
        static QMutex mutex;
        mutex.lock();
        if (nullptr == log_writer)
            log_writer = new LogWriter;

        mutex.unlock();
    }
    return log_writer;
}

void LogWriter::writeLog(const QString& word, LOG_LEVEL logLevel)
{
    QDateTime dateTime = QDateTime::currentDateTime();
    QString oneWord = QString("[%1][%2] %3").arg(CSHASH_LOG_LEVEL_STR[logLevel]).arg(dateTime.toString("yy-MM-dd hh:mm:ss.zzz")).arg(word);

#ifdef LOG_TO_FILE
    QString strDir = LOGDIR + dateTime.toString("yyyy-MM");
    QString filename = dateTime.toString("dd").append(".log");
    writeToFile(oneWord, strDir, filename);
#endif

#ifdef LOG_TO_CONSOLE
    writeToConsole(oneWord);
#endif
}

void LogWriter::writeToFile(const QString& word, const QString& strDir, const QString& filename)
{
    QDir dir(strDir);
    if (!dir.exists())
        dir.mkpath(strDir);

    QFile file(dir.absolutePath() + "/" + filename);
    if (!file.exists())
    {
        file.open(QIODevice::WriteOnly);
        file.close();
    }

    file.open(QIODevice::Append);
    file.write((word + '\n').toUtf8());
    file.close();
}

void LogWriter::writeToConsole(const QString& word)
{
    qDebug().noquote() << word;
}
